/*
 * @Author: DUST
 * @Date: 2023-06-09 14:40:03
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-17 16:28:55
 * @FilePath: \koa-node-ts\utils\index.ts
 * @Description:
 * undefined
 */

import Tags from "../app/model/Tags";
import { tagItem } from "../app/validator/TagsValidator";

/**
 * @description: 获取随机十六进制颜色
 */
export const color16 = () => {
  //十六进制颜色随机
  const r = Math.floor(Math.random() * 200);
  const g = Math.floor(Math.random() * 200);
  const b = Math.floor(Math.random() * 200);
  const color = `#${r.toString(16).padStart(2, "0")}${g
    .toString(16)
    .padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
  // console.log(color);
  return color;
};

export const tagsPresetsColor = () => {
  const arr = ["pink", "red", "orange", "green", "cyan", "blue", "purple"];

  const index = Math.ceil(Math.random() * arr.length);
  if (index > arr.length - 1) return arr[index - 1];
  return arr[index];
};
/**
 * @description: 给他跟标签添加默认颜色
 * @param {Array} tagList：需要添加颜色的标签
 * @param {true} isDefault：是否使用默认颜色
 */
export const tagsAddColor = (
  tagList: Array<Tags> | undefined,
  isDefault: boolean = true
): Array<Tags> => {
  const arr: Array<Tags> = [];

  if (tagList) {
    for (let index = 0; index < tagList.length; index++) {
      const val = tagList[index];
      if (isDefault) val.dataValues.color = tagsPresetsColor();
      else val.dataValues.color = color16();
      arr.push(val);
    }
  }
  // console.log("===", arr);
  return arr;
};

// 判断的是否是JSON字符串
export const isJSONStr = (str: string) => {
  if (typeof str == "string") {
    try {
      const obj = JSON.parse(str);
      // 等于这个条件说明就是JSON字符串 会返回true
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        //不是就返回false
        return false;
      }
    } catch (e) {
      return false;
    }
  }
  return false;
};
